package com.zyf.lj.service.impl;

import com.zyf.lj.config.WxMiniappConfig;
import com.zyf.lj.entity.User;
import com.zyf.lj.mapper.UserMapper;
import com.zyf.lj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private WxMiniappConfig wxMiniappConfig;
    
    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }
    
    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }
    
    @Override
    @Transactional
    public boolean addUser(User user) {
        // 设置默认状态为正常
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        return userMapper.insert(user) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateUser(User user) {
        return userMapper.update(user) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteUser(Long id) {
        return userMapper.deleteById(id) > 0;
    }
    
    @Override
    @Transactional
    public User wxLogin(String code) {
        return wxLogin(code, null);
    }
    
    @Override
    @Transactional
    public User wxLogin(String code, Map<String, Object> wxUserInfo) {
        log.info("微信登录，code: {}, userInfo: {}", code, wxUserInfo);
        
        try {
            // 开发环境下，可以使用模拟数据
            if ("dev_code".equals(code)) {
                User mockUser = new User();
                mockUser.setId(999L);
                mockUser.setOpenid("mock_openid_" + System.currentTimeMillis());
                mockUser.setNickname("微信用户");
                mockUser.setAvatar("/static/images/avatar.png");
                mockUser.setStatus(1);
                return mockUser;
            }
            
            // 构建请求参数
            String url = wxMiniappConfig.getLoginUrl() + 
                    "?appid=" + wxMiniappConfig.getAppid() + 
                    "&secret=" + wxMiniappConfig.getSecret() + 
                    "&js_code=" + code + 
                    "&grant_type=authorization_code";
            
            log.info("调用微信登录API: {}", url);
            
            try {
                // 发送请求到微信服务器
                Map<String, Object> response = restTemplate.getForObject(url, HashMap.class);
                log.info("微信登录响应: {}", response);
                
                if (response == null) {
                    log.error("微信登录响应为空");
                    return null;
                }
                
                // 检查是否有错误
                if (response.containsKey("errcode") && !response.get("errcode").equals(0)) {
                    log.error("微信登录错误: {}, {}", response.get("errcode"), response.get("errmsg"));
                    return null;
                }
                
                if (!response.containsKey("openid")) {
                    log.error("微信登录响应中没有openid: {}", response);
                    return null;
                }
                
                String openid = (String) response.get("openid");
                String sessionKey = (String) response.get("session_key");
                log.info("获取到openid: {}, session_key: {}", openid, sessionKey);
                
                // 处理微信用户信息
                Map<String, Object> userInfoMap = null;
                String nickname = "微信用户";
                String avatarUrl = "/static/images/avatar.png";
                
                if (wxUserInfo != null && wxUserInfo.containsKey("encryptedData") && wxUserInfo.containsKey("iv")) {
                    try {
                        // 这里可以解密获取用户信息，但需要引入相关解密工具
                        // 由于解密需要额外的工具类，这里简化处理，直接从rawData中提取信息
                        String rawData = (String) wxUserInfo.get("rawData");
                        if (rawData != null && !rawData.isEmpty()) {
                            // 简单解析rawData（实际上应该使用JSON解析库）
                            if (rawData.contains("nickName")) {
                                int nickNameStart = rawData.indexOf("\"nickName\":\"") + 12;
                                int nickNameEnd = rawData.indexOf("\"", nickNameStart);
                                if (nickNameStart > 12 && nickNameEnd > nickNameStart) {
                                    nickname = rawData.substring(nickNameStart, nickNameEnd);
                                }
                            }
                            
                            if (rawData.contains("avatarUrl")) {
                                int avatarStart = rawData.indexOf("\"avatarUrl\":\"") + 13;
                                int avatarEnd = rawData.indexOf("\"", avatarStart);
                                if (avatarStart > 13 && avatarEnd > avatarStart) {
                                    avatarUrl = rawData.substring(avatarStart, avatarEnd);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析用户信息失败: {}", e.getMessage(), e);
                    }
                }
                
                // 查询是否已存在该微信用户
                User user = null;
                try {
                    user = userMapper.selectByOpenid(openid);
                } catch (TooManyResultsException e) {
                    // 处理多个相同openid的情况
                    log.warn("发现多个相同openid的用户记录，尝试获取第一个活跃用户");
                    List<User> users = userMapper.selectAll();
                    for (User u : users) {
                        if (openid.equals(u.getOpenid()) && u.getStatus() == 1) {
                            user = u;
                            break;
                        }
                    }
                    
                    if (user == null && !users.isEmpty()) {
                        // 如果没有找到活跃用户，使用第一个匹配的用户
                        for (User u : users) {
                            if (openid.equals(u.getOpenid())) {
                                user = u;
                                break;
                            }
                        }
                    }
                }
                
                if (user == null) {
                    // 不存在则创建新用户
                    user = new User();
                    user.setOpenid(openid);
                    user.setNickname(nickname);
                    user.setAvatar(avatarUrl);
                    user.setStatus(1);
                    user.setCreateTime(LocalDateTime.now());
                    user.setUpdateTime(LocalDateTime.now());
                    
                    log.info("创建新用户: {}", user);
                    
                    try {
                        // 保存用户
                        userMapper.insert(user);
                    } catch (Exception e) {
                        log.error("保存用户失败: {}", e.getMessage(), e);
                        return null;
                    }
                } else {
                    // 已存在用户，更新用户信息
                    boolean needUpdate = false;
                    
                    // 只有当获取到了有效的昵称和头像时才更新
                    if (!"微信用户".equals(nickname) && !nickname.equals(user.getNickname())) {
                        user.setNickname(nickname);
                        needUpdate = true;
                    }
                    
                    if (!"/static/images/avatar.png".equals(avatarUrl) && !avatarUrl.equals(user.getAvatar())) {
                        user.setAvatar(avatarUrl);
                        needUpdate = true;
                    }
                    
                    if (needUpdate) {
                        user.setUpdateTime(LocalDateTime.now());
                        userMapper.update(user);
                    }
                }
                
                return user;
            } catch (HttpClientErrorException e) {
                log.error("微信API调用失败: {}, 响应: {}", e.getMessage(), e.getResponseBodyAsString(), e);
                return null;
            } catch (RestClientException e) {
                log.error("微信API调用异常: {}", e.getMessage(), e);
                return null;
            }
        } catch (Exception e) {
            log.error("微信登录处理异常: {}", e.getMessage(), e);
        }
        
        return null;
    }
} 